package cn.yzgy.yzgyoa.ucenter.dto;

import cn.yzgy.yzgyoa.ucenter.entity.UserInfoDetail;
import cn.yzgy.yzgyoa.ucenter.service.impl.SysUserDetailServiceImpl;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.shiro.session.Session;

import java.util.Date;

/**
 * 在线用户DTO
 *
 * @author Yqsen
 * @since 2019-12-19 09:02:37
 */
@Data
@Accessors(chain = true)
public class OnlineUserDto {

    public static final String ATTRIBUTE_KEY = "org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY";
    public static final String PRIMARY_PRINCIPAL_KEY = "primaryPrincipal";

    /**
     * 会话ID
     */
    private String sessionId;

    /**
     * UID
     */
    private String uid;

    /**
     * 登录名
     */
    private String loginName;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 部门名
     */
    private String deptName;

    /**
     * 登录IP
     */
    private String host;

    /**
     * 登录时间
     */
    private Date loginTime;

    /**
     * 最后访问时间
     */
    private Date lastAccessTime;

    /**
     * 将Session信息转换为在线用户信息
     *
     * @param session Shiro-Session
     * @return 转换后的在线用户对象
     */
    public static OnlineUserDto trans(Session session, SysUserDetailServiceImpl sysUserDetailService) {
        String sessionId = session.getId().toString();
        OnlineUserDto userDto = new OnlineUserDto()
                .setSessionId(sessionId.substring(sessionId.lastIndexOf("-") + 1))
                .setLoginTime(session.getStartTimestamp())
                .setLastAccessTime(session.getLastAccessTime())
                .setHost(session.getHost());
        JSONObject object = (JSONObject)JSONObject.toJSON(session.getAttribute(ATTRIBUTE_KEY));
        JSONObject principal = (JSONObject) JSONObject.toJSON(object.get(PRIMARY_PRINCIPAL_KEY));
        userDto.setUid(principal.getString("id"))
                .setLoginName(principal.getString("loginName"));
        UserInfoDetail userInfoDetail = sysUserDetailService.getUserDetailInfoByUid(Long.parseLong(userDto.getUid()));
        return userDto.setUserName(userInfoDetail.getUserName()).setDeptName(userInfoDetail.getDeptName());
    }
}
